package regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTest {

	public static void main(String[] args) {
		// 要验证的字符串
//		String str = "http://www.baidu.com/s?wd=java.io.FileNotFoundException%3A%20E%3A%5CAA%E6%89%93%E5%8C%85%E6%96%87%E4%BB%B6%E5%A4%B9%5Ctest%20(%E6%8B%92%E7%BB%9D%E8%AE%BF%E9%97%AE%E3%80%82)&rsv_spt=1&rsv_iqid=0xb0eaf3a40000b9f4&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_n=2&rsv_sug3=1";
//		 String str = "http://xx.cn/a?a=aa&b=bb";
		String str = "http://xx.cn";
		// isUrl(str);
//		 getUrl(str);
		 getDomain(str);
	}

	/** 判断是否是URL地址
	 * @param str
	 * @return
	 */
	public static boolean isUrl(String str) {
		// 验证规则
		String regex = "https?:\\/\\/.+";// 匹配： http(s)://其他
		return Pattern.matches(regex, str);
	}

	/** 获取URL地址，排除参数
	 * @param str
	 */
	public static void getUrl(String str) {
		String result = "";
		String regex = "https?:\\/\\/.+\\?";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		if(m.find()) {
			result = m.group().replace("?", "");
		} else {
			regex = "https?:\\/\\/.+";
			if(Pattern.matches(regex, str)) {
				result = str;
			}
		}
		System.out.println("url>> " + result);
	}
	
	/**获取域名
	 * @param str 待匹配的串
	 */
	public static void getDomain(String str) {
		String result = "";
		String regex = "https?:\\/\\/.+\\/";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		if(m.find()) {
			String s = m.group();
			result = s.substring(0, s.lastIndexOf("/"));
		} else {
			regex = "https?:\\/\\/.+\\?";
			p = Pattern.compile(regex);
			m = p.matcher(str);
			if(m.find()) {
				result = m.group().replace("?", "");
			} else {
				regex = "https?:\\/\\/.+";
				if(Pattern.matches(regex, str)) {
					result = str;
				}
			}
		}
		System.out.println("domain>> " + result);
	}

}
